using System;
using System.Configuration;
using System.Linq;

namespace MT5Trade.Models
{
    /// <summary>
    /// 交易模式控制器 - 管理手动和优化交易模式切换
    /// </summary>
    public class TradingModeController
    {
        // 交易模式枚举
        public enum TradingMode
        {
            Manual = 0,    // 手动模式 - 使用固定参数
            Basic = 1,     // 基础优化 - 仅凯利公式
            Advanced = 2,  // 高级优化 - 凯利公式 + GARCH波动率
            Full = 3       // 完全优化 - 所有优化方法
        }

        private TradingMode _currentMode;
        private readonly BonusArbitrageOptimizer _optimizer;
        private readonly DynamicGapAdjuster _dynamicGapAdjuster;

        // 优化功能开关
        public bool IsKellyFormulaEnabled { get; private set; }
        public bool IsGARCHEnabled { get; private set; }
        public bool IsVaREnabled { get; private set; }
        public bool IsDynamicGapEnabled { get; private set; }
        public bool IsMarketRegimeEnabled { get; private set; }

        // 当前模式
        public TradingMode CurrentMode
        {
            get => _currentMode;
            set
            {
                _currentMode = value;
                UpdateOptimizationFlags();
                SaveModeToConfig();
            }
        }

        public TradingModeController()
        {
            _optimizer = new BonusArbitrageOptimizer();
            _dynamicGapAdjuster = new DynamicGapAdjuster();
            LoadConfiguration();
        }

        /// <summary>
        /// 从配置文件加载设置
        /// </summary>
        private void LoadConfiguration()
        {
            try
            {
                // 读取交易模式
                string modeStr = ConfigurationManager.AppSettings["TradingMode"] ?? "Manual";
                if (Enum.TryParse<TradingMode>(modeStr, out TradingMode mode))
                {
                    _currentMode = mode;
                }
                else
                {
                    _currentMode = TradingMode.Manual;
                }

                // 读取各个优化开关（可以覆盖模式默认设置）
                string kellyStr = ConfigurationManager.AppSettings["Optimization.EnableKellyFormula"];
                string garchStr = ConfigurationManager.AppSettings["Optimization.EnableGARCH"];
                string varStr = ConfigurationManager.AppSettings["Optimization.EnableVaR"];
                string dynamicStr = ConfigurationManager.AppSettings["Optimization.EnableDynamicGap"];
                string regimeStr = ConfigurationManager.AppSettings["Optimization.EnableMarketRegime"];

                // 如果配置文件中有明确设置，使用配置值；否则根据模式设置
                if (!string.IsNullOrEmpty(kellyStr))
                    IsKellyFormulaEnabled = bool.Parse(kellyStr);
                if (!string.IsNullOrEmpty(garchStr))
                    IsGARCHEnabled = bool.Parse(garchStr);
                if (!string.IsNullOrEmpty(varStr))
                    IsVaREnabled = bool.Parse(varStr);
                if (!string.IsNullOrEmpty(dynamicStr))
                    IsDynamicGapEnabled = bool.Parse(dynamicStr);
                if (!string.IsNullOrEmpty(regimeStr))
                    IsMarketRegimeEnabled = bool.Parse(regimeStr);

                // 如果没有明确设置，根据模式更新标志
                if (string.IsNullOrEmpty(kellyStr) || string.IsNullOrEmpty(garchStr))
                {
                    UpdateOptimizationFlags();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载交易模式配置失败: {ex.Message}");
                SetDefaultConfiguration();
            }
        }

        /// <summary>
        /// 设置默认配置
        /// </summary>
        private void SetDefaultConfiguration()
        {
            _currentMode = TradingMode.Manual;
            UpdateOptimizationFlags();
        }

        /// <summary>
        /// 根据当前模式更新优化标志
        /// </summary>
        private void UpdateOptimizationFlags()
        {
            switch (_currentMode)
            {
                case TradingMode.Manual:
                    IsKellyFormulaEnabled = false;
                    IsGARCHEnabled = false;
                    IsVaREnabled = false;
                    IsDynamicGapEnabled = false;
                    IsMarketRegimeEnabled = false;
                    break;

                case TradingMode.Basic:
                    IsKellyFormulaEnabled = true;
                    IsGARCHEnabled = false;
                    IsVaREnabled = false;
                    IsDynamicGapEnabled = false;
                    IsMarketRegimeEnabled = false;
                    break;

                case TradingMode.Advanced:
                    IsKellyFormulaEnabled = true;
                    IsGARCHEnabled = true;
                    IsVaREnabled = true;
                    IsDynamicGapEnabled = false;
                    IsMarketRegimeEnabled = false;
                    break;

                case TradingMode.Full:
                    IsKellyFormulaEnabled = true;
                    IsGARCHEnabled = true;
                    IsVaREnabled = true;
                    IsDynamicGapEnabled = true;
                    IsMarketRegimeEnabled = true;
                    break;
            }
        }

        /// <summary>
        /// 保存模式到配置文件
        /// </summary>
        private void SaveModeToConfig()
        {
            try
            {
                var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                // 更新交易模式
                config.AppSettings.Settings["TradingMode"].Value = _currentMode.ToString();

                // 更新优化开关
                config.AppSettings.Settings["Optimization.EnableKellyFormula"].Value = IsKellyFormulaEnabled.ToString();
                config.AppSettings.Settings["Optimization.EnableGARCH"].Value = IsGARCHEnabled.ToString();
                config.AppSettings.Settings["Optimization.EnableVaR"].Value = IsVaREnabled.ToString();
                config.AppSettings.Settings["Optimization.EnableDynamicGap"].Value = IsDynamicGapEnabled.ToString();
                config.AppSettings.Settings["Optimization.EnableMarketRegime"].Value = IsMarketRegimeEnabled.ToString();

                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"保存交易模式配置失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 计算优化的敞口大小
        /// </summary>
        /// <param name="symbol">交易品种</param>
        /// <param name="baseGap">基础敞口</param>
        /// <param name="marketData">市场数据（可选）</param>
        /// <returns>优化后的敞口大小</returns>
        public double CalculateOptimalGap(string symbol, double baseGap, object marketData = null)
        {
            // 手动模式直接返回基础敞口
            if (_currentMode == TradingMode.Manual)
            {
                return baseGap;
            }

            double optimalGap = baseGap;

            try
            {
                // 应用凯利公式优化
                if (IsKellyFormulaEnabled)
                {
                    // 获取历史胜率（示例值，实际应从历史数据计算）
                    double winProbability = 0.52; // 52%胜率
                    double avgWin = 0.015; // 平均盈利1.5%
                    double avgLoss = 0.010; // 平均亏损1.0%

                    // 使用凯利公式：f* = (p*b - q) / b
                    double b = avgWin / avgLoss; // 赔率
                    double p = winProbability;
                    double q = 1 - p;
                    double kellyFactor = (p * b - q) / b;
                    kellyFactor = Math.Max(0, kellyFactor) * 0.25; // 应用安全系数
                    optimalGap = Math.Min(baseGap * (1 + kellyFactor), 0.25); // 最大不超过25%
                }

                // 应用GARCH波动率调整
                if (IsGARCHEnabled && marketData != null)
                {
                    // 示例：根据波动率调整敞口
                    // 高波动率时减小敞口，低波动率时增大敞口
                    double[] returns = GetRecentReturns(symbol, 100); // 获取最近100个收益率
                    if (returns != null && returns.Length > 0)
                    {
                        double volatility = _optimizer.PredictVolatilityGARCH(
                            returns,
                            0.000002, // omega
                            0.08,     // alpha
                            0.90      // beta
                        );

                        // 波动率调整因子
                        double targetVol = 0.01; // 目标波动率1%
                        double volAdjustment = Math.Min(targetVol / volatility, 1.5);
                        optimalGap *= volAdjustment;
                    }
                }

                // 应用VaR风险限制
                if (IsVaREnabled)
                {
                    double portfolioValue = GetPortfolioValue();
                    double maxRiskAmount = portfolioValue * 0.02; // 最大风险2%
                    double positionVaR = CalculatePositionVaR(symbol, optimalGap);

                    if (positionVaR > maxRiskAmount)
                    {
                        optimalGap *= (maxRiskAmount / positionVaR);
                    }
                }

                // 应用动态敞口调整
                if (IsDynamicGapEnabled)
                {
                    // 根据最近表现调整
                    bool lastTradeWon = GetLastTradeResult();
                    long currentTimestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
                    optimalGap = _dynamicGapAdjuster.AdjustForRecentPerformance(optimalGap, lastTradeWon, currentTimestamp);
                }

                // 应用市场状态检测
                if (IsMarketRegimeEnabled)
                {
                    string marketRegime = DetectMarketRegime(symbol);
                    switch (marketRegime)
                    {
                        case "Trending":
                            optimalGap *= 1.2; // 趋势市场增大敞口
                            break;
                        case "Oscillating":
                            optimalGap *= 0.8; // 震荡市场减小敞口
                            break;
                        case "HighVolatility":
                            optimalGap *= 0.5; // 高波动减小敞口
                            break;
                    }
                }

                // 确保敞口在允许范围内
                optimalGap = Math.Max(0.05, Math.Min(0.25, optimalGap));
            }
            catch (Exception ex)
            {
                Console.WriteLine($"优化敞口计算失败，使用默认值: {ex.Message}");
                return baseGap;
            }

            return optimalGap;
        }

        /// <summary>
        /// 获取模式描述
        /// </summary>
        public string GetModeDescription()
        {
            switch (_currentMode)
            {
                case TradingMode.Manual:
                    return "手动模式 - 使用固定参数交易";
                case TradingMode.Basic:
                    return "基础优化 - 启用凯利公式优化";
                case TradingMode.Advanced:
                    return "高级优化 - 凯利公式 + GARCH波动率 + VaR风控";
                case TradingMode.Full:
                    return "完全优化 - 所有优化方法启用";
                default:
                    return "未知模式";
            }
        }

        /// <summary>
        /// 切换到下一个模式
        /// </summary>
        public void CycleMode()
        {
            int nextMode = ((int)_currentMode + 1) % Enum.GetValues(typeof(TradingMode)).Length;
            CurrentMode = (TradingMode)nextMode;
        }

        // 辅助方法（实际实现需要连接到真实数据源）
        private double[] GetRecentReturns(string symbol, int count)
        {
            // TODO: 从历史数据获取收益率
            return new double[0];
        }

        private double GetPortfolioValue()
        {
            // TODO: 获取账户总值
            return 10000.0;
        }

        private double CalculatePositionVaR(string symbol, double gap)
        {
            // TODO: 计算头寸VaR
            return gap * 100;
        }

        private bool GetLastTradeResult()
        {
            // TODO: 获取上一笔交易结果
            return true;
        }

        private string DetectMarketRegime(string symbol)
        {
            // TODO: 检测市场状态
            return "Normal";
        }
    }
}